package riteh.eventNetwork.client;

import android.app.Activity;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.TextView;
import android.content.Intent;
import android.content.SharedPreferences;
import riteh.eventNetwork.client.R;

public class ActivityLogin extends Activity {
	
	private Button btnLogin;
	//private Button btnLoginIvan, btnLoginVedran, btnLoginJean;
	private EditText editEmail, editPassword;
	private SharedPreferences settings;
	private CheckBox checkRemember;
	private TextView labelCreate;
	private Intent intentTabs, intentRegister, intentSettings, intentAbout;
    
/* ********************** OVERRIDE FUNCTIONS ******************************/
    
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d(C.TAG, "LOGIN Activity");
        setContentView(R.layout.login);
        
    // INSTANCIRANJE OBJEKTA **************************
        
        btnLogin = (Button) findViewById(R.id.loginButtonLogin);
        labelCreate = (TextView) findViewById(R.id.loginLabelCreateNewAccount);
        editEmail = (EditText) findViewById(R.id.loginEditEmail);
        editPassword = (EditText) findViewById(R.id.loginEditPassword);
        checkRemember = (CheckBox) findViewById(R.id.loginCheckRememberMe);
        settings = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
        intentTabs = new Intent(this, ActivityTabs.class);
        intentRegister = new Intent(this, ActivityUserEdit.class);
        intentSettings = new Intent(this, ActivitySettings.class);
        intentAbout = new Intent(this, ActivityAbout.class);
        
      /*btnLoginIvan = (Button) findViewById(R.id.loginButtonLoginIvan);
        btnLoginVedran = (Button) findViewById(R.id.loginButtonLoginVedran);
        btnLoginJean = (Button) findViewById(R.id.loginButtonLoginJean);*/
       
    // ACTIONS ON STARTUP *****************************
        String email, pass;
        email = settings.getString("accountEmail", "");
        pass = settings.getString("accountPassword", "");
        
        editEmail.setText(email);
        editPassword.setText(pass);
        
        if (!email.isEmpty() && !pass.isEmpty()) {
	        boolean autoLogin = settings.getBoolean("settingsCheckAutoLogin", false);
	            if (autoLogin) {
	            	login();
	            }        
        }
        
    // EVENT LISTENERS ********************************
        
        checkRemember.setOnCheckedChangeListener( new OnCheckedChangeListener() {
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				if (!isChecked) {
					settings.edit().putString("accountEmail","");
					settings.edit().putString("accountPassword", "");
				}
			}
		});
        
        btnLogin.setOnClickListener( new OnClickListener() {
			public void onClick(View v) {
				login();
			}
		});
        
        /*
        btnLoginJean.setOnClickListener( new OnClickListener() {	
			public void onClick(View v) {
				editEmail.setText("jean");
				editPassword.setText("jean");
				login();
			}
		});
        
        btnLoginIvan.setOnClickListener( new OnClickListener() {	
			public void onClick(View v) {
				editEmail.setText("ivan");
				editPassword.setText("ivan");
				login();
			}
		});
        
        btnLoginVedran.setOnClickListener( new OnClickListener() {
			public void onClick(View v) {
				editEmail.setText("vedran");
				editPassword.setText("vedran");
				login();
			}
		});
       */
                
        labelCreate.setOnClickListener( new OnClickListener() {
			public void onClick(View v) {
				intentRegister.putExtra("userId", 0);
				intentRegister.putExtra("userInfoId", 0);
				startActivityForResult(intentRegister, C.ACTIVITY_REGISTER);
			}
		});        
    }
	
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    	super.onActivityResult(requestCode, resultCode, data);
    	Log.d(C.TAG,"LOGIN: onActivityResult: request: " + requestCode + ", result: " + resultCode);

    	if (requestCode == C.ACTIVITY_REGISTER) {
    		if (resultCode == C.SUCCESS) {
                String email = data.getStringExtra("email");
                String pass = data.getStringExtra("password");
          
                editEmail.setText(email);
                editPassword.setText(pass);
        
                login();
    		}
    		else if (resultCode == C.ERROR) {
    			return;
    		}
    		else return;
    	}
    	else if (requestCode == C.ACTIVITY_TABS) {
    		finish();
    	}
    }

    public boolean onCreateOptionsMenu(Menu menu) {
    	super.onCreateOptionsMenu(menu);
    	MenuInflater inflater = new MenuInflater(this);
    	inflater.inflate(R.menu.login, menu);
    	return true; 
    }
    
    public boolean onOptionsItemSelected(MenuItem item) {
    	switch (item.getItemId()) {
    	case R.id.loginMenuSettings:
    		startActivity(intentSettings);
    		return true;
    	case R.id.loginMenuAbout:
    		startActivity(intentAbout);
    		return true;
    	}
    	return super.onOptionsItemSelected(item);
    }
    
/* ********************** PRIVATE FUNCTIONS *******************************/
    
	// TODO - Remember me function
    
    private void login() {
    	Log.d(C.TAG, "LOGIN: login()");
    	
        String email = editEmail.getText().toString();
        String password = editPassword.getText().toString();
  
        if (email.isEmpty() || password.isEmpty()) {
        	C.toast(this, R.string.toastLoginEmailPasswordEmpty);
            return;
        }

        String passwordHash = C.SHA1.compute(password);
        
        if (passwordHash.length() != 40) {
        	C.toast(this, R.string.toastPasswordHashError);
        	return;
        }
        
        RestClient client = new RestClient(getString(R.string.serverMethodLogin));
        client.AddParam("email", email);
        client.AddParam("password", passwordHash);
        
        String result = C.getMethod0(client, "login");
        
        if (C.resultSuccess(this, result, getString(R.string.toastLoginWrongUserOrPass))) {
        	
        	if (checkRemember.isChecked()) {
        		settings.edit().putString("accountEmail", email);
        		settings.edit().putString("accountPassword", password);
        	}
        	
        	long userId = Long.parseLong(result);
        	if (userId == 0) {
        		C.toast(this, R.string.toastLoginWrongUserOrPass);
            	return;
        	}
        	else {
            	intentTabs.putExtra("id", userId);
            	intentTabs.putExtra("tab", "home");
            	startActivityForResult(intentTabs, C.ACTIVITY_TABS);   
        	}
        }
    }
            
}